package com.jiexinyun.ftp;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPSClient;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.List;

@Slf4j
@Component
public class FtpClient {

    private static String host = "192.168.0.118";
    private static int port = 21; // FTP默认端口
    private static String username = "ftptest";
    private static String password = "dell@2025";
    private static boolean passiveMode = true; // 使用被动模式

    /**
     * 创建目录路径
     * @param pathList 路径列表
     */
    public static void createPaths(List<String> pathList) {
        FTPSClient ftpClient = new FTPSClient();
        try {
            connect(ftpClient);

            // 创建目录
            for (String path : pathList) {
                makeDirectories(ftpClient, path);
            }

            // 上传文件示例
            String localFilePath = "D:/test.txt";
            String remoteFilePath = "/files/test.txt";
            uploadFile(ftpClient, localFilePath, remoteFilePath);

            log.info("操作成功");
        } catch (IOException e) {
            log.error("操作失败", e);
        } finally {
            disconnect(ftpClient);
        }
    }

    public static void main(String[] args) throws IOException {
//        uploadFile();

        FTPClient ftpClient = new FTPClient(); // 而不是FTPSClient
        try {
            ftpClient.connect(host, port);
            boolean isLogin = ftpClient.login(username, password);
            System.out.println(isLogin);
            System.out.println("11111111111111");
        } catch (Exception e) {
            log.info("48151",e);
        } finally {

        }
        ftpClient.logout();
        ftpClient.disconnect();
    }

    public static void uploadFile() {
        FTPSClient ftpsClient = new FTPSClient();
        try {
            ftpsClient.setConnectTimeout(10000);
            ftpsClient.setDataTimeout(Duration.ofSeconds(10000));
            ftpsClient.setControlEncoding("UTF-8");

            connect(ftpsClient);

            // FTPS 必须配置的加密命令
            ftpsClient.execPBSZ(0);       // 设置保护缓冲区大小
            ftpsClient.execPROT("P");      // 启用数据通道加密（P = Private）

            ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (passiveMode) {
                ftpsClient.enterLocalPassiveMode();
            }

            // 上传文件
            String localFilePath = "D:/test.txt";
            String remoteFilePath = "/jiexinyun/aaa/test.txt";
            uploadFile(ftpsClient, localFilePath, remoteFilePath);

            log.info("文件上传成功");
        } catch (IOException e) {
            log.error("上传失败", e);
        } finally {
            disconnect(ftpsClient);
        }
    }

    public static void downloadFile() {
        FTPSClient ftpsClient = new FTPSClient();
        try {
            connect(ftpsClient);

            // 下载文件
            String remoteFilePath = "/ftp/jiexinyun/test.txt";
            String localFilePath = "D:/downloaded_test.txt";
            downloadFile(ftpsClient, remoteFilePath, localFilePath);

            log.info("文件下载成功");
        } catch (IOException e) {
            log.error("下载失败", e);
        } finally {
            disconnect(ftpsClient);
        }
    }

    // ================ 辅助方法 ================

    private static void connect(FTPSClient ftpsClient) throws IOException {
        ftpsClient.connect(host, port);
        System.out.println(ftpsClient.isConnected());
        boolean isLogin = ftpsClient.login(username, password);
        System.out.println("登录响应: " + ftpsClient.getReplyString());
        System.out.println(isLogin);
    }

    private static void disconnect(FTPSClient ftpClient) {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            log.error("断开连接失败", e);
        }
    }

    private static void makeDirectories(FTPClient ftpClient, String path) throws IOException {
        String[] directories = path.split("/");
        for (String dir : directories) {
            if (!dir.isEmpty()) {
                boolean exists = ftpClient.changeWorkingDirectory(dir);
                if (!exists) {
                    System.out.println(ftpClient.printWorkingDirectory());
                    ftpClient.makeDirectory(dir);
                    ftpClient.changeWorkingDirectory(dir);
                }
            }
        }
    }

    private static void uploadFile(FTPClient ftpClient, String localFilePath, String remoteFilePath) throws IOException {
        File localFile = new File(localFilePath);
        try (FileInputStream inputStream = new FileInputStream(localFile)) {
            // 确保目录存在
            int lastSlash = remoteFilePath.lastIndexOf('/');
            if (lastSlash > 0) {
                String remoteDir = remoteFilePath.substring(0, lastSlash);
                makeDirectories(ftpClient, remoteDir);
                ftpClient.changeWorkingDirectory(remoteDir);
            }

            // 上传文件
            String remoteFileName = remoteFilePath.substring(lastSlash + 1);
            boolean success = ftpClient.storeFile(remoteFileName, inputStream);
            if (!success) {
                throw new IOException("上传失败: " + ftpClient.getReplyString());
            }
        }
    }

    private static void downloadFile(FTPClient ftpClient, String remoteFilePath, String localFilePath) throws IOException {
        File localFile = new File(localFilePath);
        try (FileOutputStream outputStream = new FileOutputStream(localFile)) {
            ftpClient.retrieveFile(remoteFilePath, outputStream);
        }
    }

}
